#include "Source/Texture.h"
#include "Source/IO/File.h"
#include "json.h"
#include <SDL.h>

Texture::Texture() :
m_isLoaded(false),
m_Id(-1),
m_filename("")
{
	
}

Texture::~Texture()
{
	if(m_isLoaded)
		Unload();
}

bool Texture::IsLoaded()
{
	return m_isLoaded;
}

int Texture::GetId()
{
	return m_Id;
}

std::string Texture::GetFilename()
{
	return m_filename;
}

SDL_Surface* Texture::GetTexture()
{
	return m_texture;
}

void Texture::Load(std::string filename)
{
	CL_File* file = CL_File::Open(filename.c_str(), E_FileModes_ReadText);
	std::string jsonDoc="";
	while(!file->IsEOF())
	{
		std::string line;
		file->ReadLine(line);
		jsonDoc.append(line);
	}

	file->Close();
	delete file;
	file=NULL;


	//Parse the document and initialize the sprite
	Json::Value data;
	Json::Reader reader;
	if(!reader.parse(jsonDoc, data, false))
	assert(false); //error parsing the Json

	m_Id			=	data["id"].asInt();
	m_filename		=	data["filename"].asString();
	int alphaRed	=	data["alpha_red"].asInt();
	int alphaGreen  =	data["alpha_green"].asInt();
	int alphaBlue	=	data["alpha_blue"].asInt();

	m_texture = SDL_LoadBMP(m_filename.c_str());
	if( m_texture == NULL )
	{
		assert(false); //Could not load texture! Wrong file maybe?
		return;
	}

	m_alphaKey = SDL_MapRGB(m_texture->format, alphaRed, alphaGreen, alphaBlue);

	EnableAlpha(true); //By default
	m_isLoaded = true;
}

void Texture::Unload()
{
	SDL_FreeSurface(m_texture);
	m_isLoaded = false;
}

void Texture::Draw(SDL_Rect* sourceRect, SDL_Surface* screen, SDL_Rect* destRect)
{
	SDL_BlitSurface(m_texture, sourceRect, screen, destRect);
}

void Texture::EnableAlpha(bool enable)
{
	SDL_SetColorKey(m_texture, enable, m_alphaKey);
}